package com.aw.baselib.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.media.MediaMetadataRetriever
import android.os.Build
import android.os.Environment
import android.util.Base64
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.aw.baselib.R
import com.aw.baselib.bean.CommonImgItemBean
import com.aw.baselib.util.AwBitmapUtils.getBitmapFromVectorDrawable
import com.aw.baselib.util.AwDataUtil.isEmpty
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.regex.Pattern

/**
 * @author : hzw.
 */
object AwImgUtil {
    /**
     * 自定义默认加载中及失败后的图片
     *
     * @param mContext
     * @param v
     * @param url
     * @param resId
     */
    fun setImgWithCustom(mContext: Context?, v: ImageView?, url: Any?, resId: Int) {
        Glide.with(mContext!!).asBitmap().load(url).placeholder(resId).error(resId).into(v!!)
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    fun setImgNoPlace(mContext: Context?, v: ImageView?, url: Any?) {
        Glide.with(mContext!!).asBitmap().load(url).into(v!!)
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    fun setImgDefaultVehicle(mContext: Context?, v: ImageView?, url: Any?) {
        Glide.with(mContext!!).asBitmap()
            .load(url).into(v!!) //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        v
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    fun setImg(mContext: Context?, v: ImageView?, url: Any?) {
        Glide.with(mContext!!).asBitmap()
            .load(url).into(v!!) //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        v
    }

    /**
     * 原尺寸展示
     * @param mContext
     * @param v
     * @param url
     */
    fun setImgOriginal(mContext: Context?, v: ImageView?, url: Any?) {
        Glide.with(mContext!!).asBitmap()
            .override(ViewGroup.LayoutParams.MATCH_PARENT, Target.SIZE_ORIGINAL)
            .load(url).into(v!!) //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        v
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url icon_img_load_error
     */
    fun setImgNoCache(mContext: Context?, v: ImageView?, url: Any?) {
        Glide.with(mContext!!).asBitmap().load(url)
            .skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用内存缓存
        .into(v!!) // 不使用磁盘缓存
        //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        v
    }

    fun setImg(mContext: Context, v: ImageView?, defaultRes: Int, url: Any?) {
        Glide.with(mContext).asBitmap().load(url)
            .placeholder(mContext.resources.getDrawable(defaultRes))
            .error(mContext.resources.getDrawable(defaultRes)).into(
            v!!
        )
    }

    fun setImgGif(context: Context?, iv: ImageView?, url: Any?) {
        Glide.with(context!!).load(url).into(iv!!)
    }

    fun isGif(localPath: String?): Boolean {
        try {
            val inputStream = FileInputStream(localPath)
            val flags = IntArray(5)
            flags[0] = inputStream.read()
            flags[1] = inputStream.read()
            flags[2] = inputStream.read()
            flags[3] = inputStream.read()
            inputStream.skip((inputStream.available() - 1).toLong())
            flags[4] = inputStream.read()
            inputStream.close()
            return flags[0] == 71 && flags[1] == 73 && flags[2] == 70 && flags[3] == 56 && flags[4] == 0x3B
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 设置圆角图片
     * @param mContext
     * @param v
     * @param url
     * @param defaultCornor
     */
    fun setImgRound(mContext: Context?, v: ImageView?, url: Any?, defaultCornor: Int) {
        //Glide设置图片圆角角度
        val roundedCorners = RoundedCorners(defaultCornor)
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(20, 20);
        val options = RequestOptions.bitmapTransform(roundedCorners)
        Glide.with(mContext!!).asBitmap()
            .load(url).apply(options) //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
        //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
        .into(v!!)
    }

    /**
     * 设置圆角头像图片
     * @param mContext
     * @param v
     * @param url
     * @param defaultCornor
     * @param defaultImgId
     */
    fun setImgRoundAvatar(
        mContext: Context,
        v: ImageView?,
        url: Any?,
        defaultCornor: Int,
        defaultImgId: Int
    ) {
        //Glide设置图片圆角角度
        val roundedCorners = RoundedCorners(defaultCornor)
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(20, 20);
        val options = RequestOptions.bitmapTransform(roundedCorners)
        Glide.with(mContext).asBitmap().load(url)
            .placeholder(mContext.resources.getDrawable(if (defaultImgId == -1) R.drawable.iv_head else defaultImgId))
            .error(mContext.resources.getDrawable(if (defaultImgId == -1) R.drawable.iv_head else defaultImgId))
            .apply(options).into(
            v!!
        )
    }

    /**
     * 默认图片加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url
     */
    fun setImgApp(mContext: Context?, v: ImageView?, url: Any?) {
        Glide.with(mContext!!).asBitmap()
            .load(url).into(v!!) //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
        //                error(mContext.getResources().getDrawable(R.mipmap.bg_video)).
        //                error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
    }

    /**
     * 默认头像加载及失败图片
     *
     * @param mContext
     * @param v
     * @param url
     */
    fun setImgAvatar(mContext: Context, v: ImageView?, url: Any?) {
        Glide.with(mContext).asBitmap().load(url)
            .placeholder(mContext.resources.getDrawable(R.drawable.iv_head))
            .error(mContext.resources.getDrawable(R.drawable.iv_head)).into(
            v!!
        )
    }

    /**
     * 回调监听图片加载, 使用默认头像加载及失败图片
     *
     * @param mContext
     * @param target
     * @param url
     */
    fun setImgToTarget(mContext: Context?, target: SimpleTarget<Bitmap?>?, url: Any?) {
        Glide.with(mContext!!).asBitmap().load(url)
            .into(target!!) //                placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
        //                error(mContext.getResources().getDrawable(R.drawable.icon_img_load_error)).
        target
    }

    fun setImgVideoFirst(mContext: Context, v: ImageView?, url: String?) {
        if (isEmpty(url)) {
            Glide.with(mContext).asBitmap()
                .load(url).into((v!!)) //                    placeholder(mContext.getResources().getDrawable(R.drawable.icon_img_load_ing)).
            //                    error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
            v
        } else {
            Glide.with(mContext).asBitmap().load(getBitmapFormUrl(url))
                .placeholder(mContext.resources.getDrawable(R.drawable.icon_img_load_ing)).into(v!!) //                    error(mContext.getResources().getDrawable(R.drawable.icon_img_no_cover)).
            v
        }
    }

    /**
     * drawable to bitmap
     *
     * @param drawable
     * @return
     */
    fun drawableToBitmap(drawable: Drawable): Bitmap {
        val bitmap = Bitmap.createBitmap(
            drawable.intrinsicWidth,
            drawable.intrinsicHeight,
            if (drawable.opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565
        )
        val canvas = Canvas(bitmap)
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
        drawable.draw(canvas)
        return bitmap
    }

    /**
     * drawable to bitmap
     *
     * @param drawable
     * @return
     */
    fun drawableToBitmap2(drawable: Drawable): Bitmap {
        val bd = drawable as BitmapDrawable
        return bd.bitmap
    }

    /**
     * 将彩色图转换为灰度图
     *
     * @param img 位图
     * @return 返回转换好的位图
     */
    fun convertGreyImg(img: Bitmap): Bitmap {
        val width = img.width //获取位图的宽
        val height = img.height //获取位图的高
        val pixels = IntArray(width * height) //通过位图的大小创建像素点数组
        img.getPixels(pixels, 0, width, 0, 0, width, height)
        val alpha = 0xFF shl 24
        for (i in 0 until height) {
            for (j in 0 until width) {
                var grey = pixels[width * i + j]
                val red = grey and 0x00FF0000 shr 16
                val green = grey and 0x0000FF00 shr 8
                val blue = grey and 0x000000FF
                grey =
                    (red.toFloat() * 0.3 + green.toFloat() * 0.59 + blue.toFloat() * 0.11).toInt()
                grey = alpha or (grey shl 16) or (grey shl 8) or grey
                pixels[width * i + j] = grey
            }
        }
        val result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        result.setPixels(pixels, 0, width, 0, 0, width, height)
        return result
    }

    /**
     * 灰度处理
     *
     * @param bmSrc
     * @return
     */
    fun bitmap2Gray(bmSrc: Bitmap): Bitmap {
        // 得到图片的长和宽
        val width = bmSrc.width
        val height = bmSrc.height
        // 创建目标灰度图像
        var bmpGray: Bitmap? = null
        bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        // 创建画布
        val c = Canvas(bmpGray)
        val paint = Paint()
        val cm = ColorMatrix()
        cm.setSaturation(0f)
        val f = ColorMatrixColorFilter(cm)
        paint.colorFilter = f
        c.drawBitmap(bmSrc, 0f, 0f, paint)
        return bmpGray
    }

    /**
     * 左1右2上3下4
     */
    fun setDrawableDirection(context: Context, tv: TextView, tag: Int, resId: Int) {
        val drawable = context.resources.getDrawable(resId)
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        when (tag) {
            1 -> tv.setCompoundDrawables(drawable, null, null, null)
            2 -> tv.setCompoundDrawables(null, null, drawable, null)
            3 -> tv.setCompoundDrawables(null, drawable, null, null)
            4 -> tv.setCompoundDrawables(null, null, null, drawable)
        }
    }

    fun cancelDrawableDirection(context: Context?, tv: TextView) {
        tv.setCompoundDrawables(null, null, null, null)
    }

    /**
     * https://blog.csdn.net/oAiTan/article/details/50517629
     * 某些机型直接获取会为null,在这里处理一下防止国内某些机型返回null
     */
    fun getViewBitmap(view: View?): Bitmap? {
        if (view == null) {
            return null
        }
        val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }

    /**
     * 把View转换成Bitmap类型
     * @paramaddViewContent要转换的View
     * @return
     */
    fun getViewBitmapFromLayout(view: View): Bitmap {
        view.isDrawingCacheEnabled = true
        view.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH
        view.measure(
            View.MeasureSpec.makeMeasureSpec(
                0,
                View.MeasureSpec.UNSPECIFIED
            ),
            View.MeasureSpec.makeMeasureSpec(
                0,
                View.MeasureSpec.UNSPECIFIED
            )
        )
        view.layout(
            0, 0,
            view.measuredWidth,
            view.measuredHeight
        )
        view.buildDrawingCache()
        val cacheBitmap = view.drawingCache
        return Bitmap.createBitmap(cacheBitmap)
    }

    fun getBitmapFromImageView(imageView: ImageView): Bitmap {
        return (imageView.drawable as BitmapDrawable).bitmap
    }

    fun getBitmapFormUrl(url: String?): Bitmap? {
        var bitmap: Bitmap? = null
        val retriever = MediaMetadataRetriever()
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, HashMap())
            } else {
                retriever.setDataSource(url)
            }

            /*getFrameAtTime()--->在setDataSource()之后调用此方法。 如果可能，该方法在任何时间位置找到代表性的帧，         并将其作为位图返回。这对于生成输入数据源的缩略图很有用。**/bitmap =
                retriever.frameAtTime
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } finally {
            try {
                retriever.release()
            } catch (e: IllegalArgumentException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return bitmap
    }

    fun setImgFromBase64(iv: ImageView?, base64Str: String) {
        if (isEmpty(base64Str) || iv == null) {
            return
        }
        val decode = Base64.decode(base64Str.split(",".toRegex()).dropLastWhile { it.isEmpty() }
            .toTypedArray()[1], Base64.DEFAULT)
        val bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.size)
        iv.setImageBitmap(bitmap)
    }

    fun getBitmapByResId(context: Context, vectorDrawableId: Int): Bitmap? {
        var bitmap: Bitmap? = null
        bitmap = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            val vectorDrawable = context.getDrawable(vectorDrawableId)
            getBitmapFromVectorDrawable(context, vectorDrawable!!)
        } else {
            BitmapFactory.decodeResource(context.resources, vectorDrawableId)
        }
        return bitmap
    }

    fun savePicture(bm: Bitmap?, fileName: String?) {
        if (null == bm) {
            AwLog.d("savePicture: ------------------图片为空------")
            return
        }
        val foder = File(Environment.getExternalStorageDirectory().absolutePath + "/grainimage")
        AwLog.d("savePicture path: " + foder.absolutePath)
        if (!foder.exists()) {
            foder.mkdirs()
        }
        val myCaptureFile = File(foder, fileName)
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile()
            }
            val bos = BufferedOutputStream(FileOutputStream(myCaptureFile))
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        AwToastUtil.show("生成图片成功!")
    }

    /**
     * <P>标签内是否全是图片类型标签</P>
     * @param html
     * @return
     */
    fun isParagraphOnlyImages(html: String): Boolean {
        if (isEmpty(html) || !html.contains("img")) {
            return false
        }
        val tempStr = html.substring(html.indexOf(">") + 1)
        AwLog.d("isParagraphOnlyImages tempStr: $tempStr")
        if (!tempStr.startsWith("<img")) {
            return false
        }
        // 正则表达式匹配<p>标签内的内容，确保其中只包含<img>标签
        val pattern = Pattern.compile("<p[^>]*>(<img[^>]+>)+</p>")
        val matcher = pattern.matcher(html)

        // 遍历所有匹配项，检查每个<p>标签是否满足条件
        while (matcher.find()) {
            val paragraph = matcher.group()
            // 如果paragraph不匹配，则跳出循环
            if (!pattern.matcher(paragraph).matches()) {
                return false
            }
        }
        return true
    }

    fun getAllImgUrlList(html: String?): List<CommonImgItemBean> {
        val list: MutableList<CommonImgItemBean> = ArrayList()
        // 定义正则表达式，用于匹配被双引号包围的文本
        val pattern = Pattern.compile("\"(.*?)\"")
        //        Pattern pattern = Pattern.compile("\"([^\"]+)\"");
        val matcher = pattern.matcher(html)

        // 创建一个列表用于保存提取的内容

        // 使用while循环查找所有匹配的字符串
        while (matcher.find()) {
            // 获取匹配的字符串并将其添加到列表中
            list.add(CommonImgItemBean(matcher.group(1)))
        }
        return list
    }
}